<script setup>
import {
  addProduct,
  updateProduct,
  productPageList
} from "@/api/user";
import {computed, reactive, ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus, Search} from "@element-plus/icons-vue";

const productList = ref({
  pageNo:1,
  pageSize:5,
  price:null,
  mainImage: '',
  origin:'',
  name:'',
  groupBuy:false,
  pointsMall:false,
  total:0
})

const product = ref({
  id:'',
  name: '',
  mainImage: '',
  productColor: '',
  productSize: '',
  inventory: null,
  price: null,
  discountRate: 1,
  origin: '',
  brand: '',
  groupBuy: false,
  pointsMall: false
})

const imageUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  product.value.mainImage = response.data.url
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('图片必须是 JPG/PNG/WEBP 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const products = ref([])

const getProductList = async () => {
  const res = await productPageList(productList.value);
  const records = res.data.records;

  for (let i = 0; i < records.length; i++) {
    const row = records[i];
    try {
      products.value = res.data.records;
      productList.value.total = res.data.total;
    } catch (e) {
      row.pointsPrice = 0;
    }
  }

  products.value = records;
  productList.value.total = res.data.total;
};

getProductList()

const pageNoChange = (value) => {
  productList.value.pageNo = value
  getProductList()
}

const pageSizeChange = (value) => {
  productList.value.pageSize = value
  getProductList()
}

const openDeleteConfirm = (productDelete) => {
  ElMessageBox.confirm(
      `<div class="delete-confirm-box">
      <p>确定要删除商品 <span class="product-name">${productDelete.name}</span> 吗？</p>
      <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
    </div>`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        customClass: 'delete-confirm-box',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            deleteProduct(productDelete.id).finally(() => {
              instance.confirmButtonLoading = false;
              done();
            });
          } else {
            done();
          }
        }
      }
  )
      .catch(() => {
        ElMessage({
          message: '已取消删除',
          type: 'info'
        });
      });
};

const deleteProduct = async (id) => {
  try {
    console.log(`删除请求 ID: ${id}, 类型: ${typeof id}`);

    const response = await axios.post(`/api/product/logicDelete/${id}`);

    if (response.data && response.data.status === true) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
      getProductList();
    } else {
      const errorMsg = response.data?.message || response.data?.data || '删除失败';
      ElMessage({
        message: errorMsg,
        type: 'error',
      });
    }
  } catch (error) {
    console.error('删除请求失败:', error);

    let errorMessage = '请求失败';
    if (error.response) {
      const data = error.response.data;
      errorMessage = data?.message || data?.data || JSON.stringify(data);
    } else if (error.request) {
      errorMessage = '服务器无响应';
    } else {
      errorMessage = error.message;
    }

    ElMessage.error(`删除失败: ${errorMessage}`);
  }
}

const dialogVisible = ref(false)

const showAddProductDialog = () => {
  resetForm()
  dialogVisible.value = true
}

const resetForm = () => {
  product.value = {
    name: '',
    mainImage: '',
    productColor: '',
    productSize: '',
    price: null,
    discountRate: 1,
    origin: '',
    brand: '',
    groupBuy: false,
    pointsMall: false
  }
  imageUrl.value = ''
}

const saveProduct = async () => {
  try {
    const valid = await productFormRef.value.validate()
    if (!valid) {
      ElMessage.error('请完善必填字段');
      return;
    }

    const payload = {
      ...product.value,
      id: isEditMode.value ? currentEditId.value : undefined
    };

    let res;
    if (isEditMode.value) {
      res = await updateProduct(currentEditId.value, payload);
    } else {
      res = await addProduct(payload);
    }
    ElMessage.success(res.message || '操作成功');
    dialogVisible.value = false;
    resetForm();
    getProductList();
  } catch (error) {
    console.error('操作失败:', error);
  }
}

const presetColors = ['红色', '蓝色', '绿色', '黑色', '白色']
const presetSizes = ['S', 'M', 'L', 'XL', 'XXL']

const isPresetColor = computed(() => {
  return presetColors.includes(product.value.productColor)
})

const isPresetSize = computed(() => {
  return presetSizes.includes(product.value.productSize)
})

const productFormRef = ref(null);
const rules = ref({
  name: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  productColor: [
    { required: true, message: '请选择或输入商品颜色', trigger: 'change' }
  ],
  productSize: [
    { required: true, message: '请选择或输入商品尺寸', trigger: 'change' }
  ],
  inventory: [
    { required: true, message: '库存不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '价格不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  pointsPrice: [
    { required: true, message: '积分价格不能为空', trigger: 'blur' },
    {
      type: 'number',
      min: 0,
      message: '积分价格不能小于0',
      trigger: 'blur',
      transform(value) {
        return Number(value);
      }
    }
  ]
});

const handleColorChange = (value) => {
  console.log('颜色选择变化:', value)
}

const handleSizeChange = (value) => {
  console.log('尺寸选择变化:', value)
}

const normalizeColorInput = () => {
  if (product.value.productColor) {
    product.value.productColor = product.value.productColor.trim()
  }
}

const normalizeSizeInput = () => {
  if (product.value.productSize) {
    product.value.productSize = product.value.productSize.trim()
  }
}

const isEditMode = ref(false)
const currentEditId = ref(null)

const handleEdit = async (index, row) => {
  isEditMode.value = true
  currentEditId.value = row.id

  try {
    product.value = {
      ...row
    }
    imageUrl.value = row.mainImage
    dialogVisible.value = true
  } catch (err) {
    ElMessage.error('加载商品信息失败')
    console.error(err)
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <h2 class="title">商品列表</h2>
      </div>
      <div class="action-bar">
        <el-form :inline="true" class="search-form">
          <!-- 查询项 -->
          <el-form-item label="价格查询">
            <el-input v-model="productList.price" placeholder="最高价格" clearable />
          </el-form-item>
          <el-form-item label="名称查询">
            <el-input v-model="productList.name" placeholder="名称模糊查询" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="getProductList">查询</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="add-btn" @click="showAddProductDialog">添加商品</el-button>
      </div>
    </template>

    <el-table
        :data="products"
        stripe
        style="width: 100%"
        v-loading="loading"
        border
    >
      <el-table-column prop="name" label="商品名称" width="180" fixed />
      <el-table-column prop="mainImage" label="商品图片" width="120">
        <template #default="scope">
          <el-image
              v-if="scope.row.mainImage"
              :src="scope.row.mainImage"
              :preview-src-list="[scope.row.mainImage]"
              fit="cover"
              class="product-image"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="productColor" label="颜色" width="100" />
      <el-table-column prop="productSize" label="尺寸" width="80" align="center" />
      <el-table-column prop="price" label="价格" width="120" align="right">
        <template #default="scope">
          ¥{{ scope.row.price?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="discountRate" label="折扣" width="80" align="center" />
      <el-table-column prop="origin" label="产地" width="120" />
      <el-table-column prop="brand" label="品牌" width="120" />
      <el-table-column prop="groupBuy" label="团购" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.groupBuy ? 'success' : 'info'" size="small">
            {{ scope.row.groupBuy ? '参与' : '不参与' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="pointsMall" label="积分商城" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.pointsMall ? 'warning' : 'info'" size="small">
            {{ scope.row.pointsMall ? '已加入' : '未加入' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="inventory" label="库存" width="100" align="center" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button-group class="action-btns">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="openDeleteConfirm(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
          v-model:current-page="productList.pageNo"
          v-model:page-size="productList.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="productList.total"
          @size-change="pageSizeChange"
          @current-change="pageNoChange"
      />
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑商品' : '添加商品'"
        width="700px"
    >
      <el-form
          ref="productFormRef"
          :model="product"
          :rules="rules"
          label-width="100px"
          label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="product.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品主图" prop="mainImage">
              <el-upload
                  class="avatar-uploader"
                  action="/api/file/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品颜色" prop="productColor">
              <el-select
                  v-model="product.productColor"
                  placeholder="请选择颜色"
                  filterable
                  allow-create
                  clearable
                  @change="handleColorChange"
                  @blur="normalizeColorInput"
              >
                <el-option v-for="color in presetColors" :key="color" :label="color" :value="color" />
              </el-select>
              <div class="input-hint" v-if="product.productColor && !isPresetColor">
                自定义颜色: {{ product.productColor }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品尺寸" prop="productSize">
              <el-select
                  v-model="product.productSize"
                  placeholder="请选择尺寸"
                  filterable
                  allow-create
                  clearable
                  @change="handleSizeChange"
                  @blur="normalizeSizeInput"
              >
                <el-option v-for="size in presetSizes" :key="size" :label="size" :value="size" />
              </el-select>
              <div class="input-hint" v-if="product.productSize && !isPresetSize">
                自定义尺寸: {{ product.productSize }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存" prop="inventory">
              <el-input-number v-model="product.inventory" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价格" prop="price">
              <el-input-number v-model="product.price" :min="0" :precision="2" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折扣率">
              <el-input-number
                  v-model="product.discountRate"
                  :min="0.1"
                  :max="1"
                  :step="0.1"
                  :precision="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品产地">
              <el-select v-model="product.origin" placeholder="请选择产地">
                <el-option label="中国" value="中国" />
                <el-option label="美国" value="美国" />
                <el-option label="日本" value="日本" />
                <el-option label="德国" value="德国" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="品牌名称">
          <el-input v-model="product.brand" placeholder="请输入品牌名称" />
        </el-form-item>

        <el-form-item label="营销设置">
          <el-checkbox v-model="product.groupBuy">参与团购</el-checkbox>
          <el-checkbox v-model="product.pointsMall">积分商城</el-checkbox>
        </el-form-item>

        <el-form-item v-if="product.pointsMall" label="积分价格" prop="pointsPrice">
          <el-input-number v-model="product.pointsPrice" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProduct">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;

  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.add-btn {
  display: inline-flex; // 改为 inline-flex 避免被收缩
  align-items: center;
  gap: 6px;
  padding: 0 12px;
  height: 32px; // 确保点击区域充足
  line-height: 32px;
  cursor: pointer;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;

  &:hover {
    transform: scale(1.05);
  }
}

.action-btns {
  display: flex;
  gap: 8px;

  .el-button {
    flex: 1;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.input-hint {
  font-size: 12px;
  color: var(--el-color-info);
  margin-top: 4px;
}

/* 上传组件样式 */
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;

    &:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
    }

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }
  }
}

/* 表格行悬停效果 */
:deep(.el-table__body tr:hover>td) {
  background-color: rgba(64, 158, 255, 0.08) !important;
}

/* 对话框样式优化 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .add-btn {
    margin-left: 0;
    width: 100%;
  }

  :deep(.el-table) {
    .el-table__cell {
      padding: 8px 0;
    }
  }
}

/* 状态标签样式增强 */
.el-tag {
  font-weight: 500;
  letter-spacing: 0.5px;

  &--success {
    background-color: rgba(103, 194, 58, 0.1);
    border-color: rgba(103, 194, 58, 0.2);
    color: var(--el-color-success);
  }

  &--warning {
    background-color: rgba(230, 162, 60, 0.1);
    border-color: rgba(230, 162, 60, 0.2);
    color: var(--el-color-warning);
  }

  &--info {
    background-color: rgba(144, 147, 153, 0.1);
    border-color: rgba(144, 147, 153, 0.2);
    color: var(--el-color-info);
  }
}

/* 数字输入框样式优化 */
:deep(.el-input-number) {
  width: 100%;

  .el-input__wrapper {
    padding-left: 8px;
    padding-right: 8px;
  }
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
}

/* 复选框样式优化 */
:deep(.el-checkbox) {
  margin-right: 16px;
}
</style>

<style>
/* 全局覆盖 - 删除确认框样式 */
.delete-confirm-box {
  line-height: 1.6;

  .product-name {
    color: var(--el-color-primary);
    font-weight: bold;
  }

  .warning-text {
    color: var(--el-color-danger);
    margin-top: 8px;
  }
}

/* 表格固定列阴影效果 */
.el-table__fixed-right::before {
  content: "";
  position: absolute;
  left: -5px;
  top: 0;
  bottom: 0;
  width: 5px;
  background: linear-gradient(to right, rgba(0, 0, 0, 0.1), transparent);
  pointer-events: none;
}
</style>
